package com.qf.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.ssm.cache.UserCache;
import com.qf.ssm.dto.ResultCode;
import com.qf.ssm.event.UserCacheEvent;
import com.qf.ssm.exceptions.AddErrorException;
import com.qf.ssm.exceptions.DeleteErrorException;
import com.qf.ssm.exceptions.UpdateErrorException;
import com.qf.ssm.mapper.UserMapper;
import com.qf.ssm.pojo.CheckStatus;
import com.qf.ssm.pojo.User;
import com.qf.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private UserCache userCache;

    @Autowired
    public UserCache getUserCache() {
        return userCache;
    }

    @Override
    public void addUser(User user) throws Exception {

        //先对数据进行判断
        boolean isNull = user.isNull(CheckStatus.ADD);
        if(isNull){

            //数据不符合我们的要求,还有必要继续执行吗?返回结果给前端
            throw new AddErrorException("数据不完整,请检查数据", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        //然后对密码进行散列
        //将数据保存到数据库中
        userMapper.addUser(user);
        context.publishEvent(new UserCacheEvent());
    }

    @Override
    public PageInfo<User> findAllUserByPage(int page, int limit) {
        PageHelper.startPage(page,limit);
        List<User> userList = userMapper.findAllUsers();
        PageInfo<User>pageInfo=new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public void deleteUsersByIds(Long[] ids) {
        if(ids==null||ids.length==0){
            //删除的时候必须有id
            throw new DeleteErrorException("删除必须传递id",ResultCode.DATA_NOT_ALLOW_NUL);
        }
         userMapper.deleteUsersByIds(Arrays.asList(ids));
        context.publishEvent(new UserCacheEvent());
    }

    @Override
    public int updateUser(User user) {
        if(user.isNull(CheckStatus.UPDATE)){
            throw new UpdateErrorException("更新的数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
         userMapper.updateUser(user);
        context.publishEvent(new UserCacheEvent());
        return 0;
    }

    @Override
    public User findUserByName(String userName) {
        return userMapper.findUserByName(userName);
    }


}
